# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : flask简单实现RabbitMQ功能.py
# @Author: dongguangwen
# @Date  : 2024-12-28 19:39
from flask import Flask, request, jsonify
import pika

app = Flask(__name__)

# RabbitMQ 配置
RABBITMQ_HOST = '192.168.1.119'
RABBITMQ_USER = 'admin'  # 修改为你的用户名
RABBITMQ_PASSWORD = 'password'  # 修改为你的密码
QUEUE_NAME = 'test_queue'


# RabbitMQ 连接
def get_rabbitmq_connection():
    credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
    return pika.BlockingConnection(pika.ConnectionParameters(host=RABBITMQ_HOST, credentials=credentials))


@app.route('/publish', methods=['POST'])
def publish_message():
    try:
        message = request.json.get('message', 'Hello, RabbitMQ!')
        connection = get_rabbitmq_connection()
        channel = connection.channel()
        channel.queue_declare(queue=QUEUE_NAME)
        channel.basic_publish(exchange='', routing_key=QUEUE_NAME, body=message)
        connection.close()
        return jsonify({'status': 'success', 'message': f'Message "{message}" sent to queue "{QUEUE_NAME}".'}), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@app.route('/consume', methods=['GET'])
def consume_message():
    try:
        connection = get_rabbitmq_connection()
        channel = connection.channel()
        channel.queue_declare(queue=QUEUE_NAME)
        method_frame, header_frame, body = channel.basic_get(queue=QUEUE_NAME, auto_ack=True)
        if body:
            message = body.decode('utf-8')
            response = {'status': 'success', 'message': message}
        else:
            response = {'status': 'success', 'message': 'No messages in the queue.'}
        connection.close()
        return jsonify(response), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


if __name__ == '__main__':
    app.run()
